package com.honey.solr.entity.method;

import java.util.List;

import com.honey.compilation.java.Method;
import com.honey.core.builder.CharacterBuilder;
import com.honey.core.builder.CharacterBuilderFactory;
import com.honey.core.calculator.JavaNameCalculator;
import com.honey.core.compiler.IndentSpace;
import com.honey.core.types.JDKFullyQualifiedJavaType;
import com.honey.core.utils.JavaBeansUtil;
import com.honey.solr.SchemaField;
import com.honey.solr.SolrFactory;

public class ToStringMethod {
private SolrFactory solrFactory = null; 
	
	public ToStringMethod( SolrFactory solrFactory ){
		this.solrFactory =  solrFactory;
	}
	
	public Method createMethod(){
		Method answer = null;
		if(  solrFactory .getSolrPlugin().isTargetEntityToString()){
			answer =new Method("toString");
			answer.setReturnType(JDKFullyQualifiedJavaType.getStringInstance());
			CharacterBuilder cb = CharacterBuilderFactory.createDefaultStringBuilder();
			cb.append( "return new StringBuilder()" );
			IndentSpace.newSpace(cb, 3);
			JavaNameCalculator javaNameCalculator=  solrFactory.getJavaNameCalculator() ;
			List<SchemaField>  columns = solrFactory.getSchemaFields();
			for(SchemaField sf : columns ){
				String fieldName =javaNameCalculator.fieldNameCalculator(sf.getName());
				String getterMethod = JavaBeansUtil.getGetterMethodName(
						fieldName,
						sf.getType()
					);
				cb.append(".append(\""+fieldName+"=\")").append(".append(this."+getterMethod+"( ) ).append(',')");
				IndentSpace.newSpace(cb, 3);
			}
			cb.append(".toString()");
			answer.addBodyLine(cb.toString());
		}
		return answer;
	}
}
